package com.baidu.push.example;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import com.baidu.android.common.logging.Log;
import com.baidu.android.pushservice.richmedia.MediaListActivity;
import com.baidu.android.pushservice.PushConstants;
import com.baidu.android.pushservice.PushManager;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.View;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import edu.hnu.cloudflight.android.R;

public class PushDemoActivity extends Activity {
	RelativeLayout mainLayout = null;
	TextView text = null;
	Button initButton = null;
	Button setButton = null;
	Button tokenButton = null;
	Button initAKButton = null;
	Button richButton = null;
	Button setTagsButton = null;
	Button delTagsButton = null;
	public static int initialCnt = 0;
	private boolean isLogin = false;

	private static final String TAG = "PushDemoActivity";
	public static final String RESPONSE_METHOD = "method";
	public static final String RESPONSE_CONTENT = "content";
	public static final String RESPONSE_ERRCODE = "errcode";
	protected static final String ACTION_LOGIN = "com.baidu.pushdemo.action.LOGIN";
	public static final String ACTION_MESSAGE = "com.baiud.pushdemo.action.MESSAGE";
	public static final String ACTION_RESPONSE = "bccsclient.action.RESPONSE";
	public static final String ACTION_SHOW_MESSAGE = "bccsclient.action.SHOW_MESSAGE";
	protected static final String EXTRA_ACCESS_TOKEN = "access_token";
	public static final String EXTRA_MESSAGE = "message";

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.main);

		initAKButton = (Button) findViewById(R.id.btn_initAK);
		initButton = (Button) findViewById(R.id.btn_init);
		richButton = (Button) findViewById(R.id.btn_rich);
		setTagsButton = (Button) findViewById(R.id.btn_setTags);
		delTagsButton = (Button) findViewById(R.id.btn_delTags);
		
		initAKButton.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {
				PushManager.startWork(getApplicationContext(),
						PushConstants.LOGIN_TYPE_API_KEY, Utils.getMetaValue(PushDemoActivity.this, "api_key"));
			}
		});
		
		initButton.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {
				if (isLogin) {
					// 已登录则清除Cookie, access token, 设置登录按钮
					CookieSyncManager.createInstance(getApplicationContext());
					CookieManager.getInstance().removeAllCookie();
					CookieSyncManager.getInstance().sync();
					LoginActivity.writeAccessToken(PushDemoActivity.this, "");

					isLogin = false;
					initButton.setText(R.string.text_btn_init);
				}
				Intent intent = new Intent(PushDemoActivity.this,
						LoginActivity.class);
				startActivity(intent);
			}
		});

		setTagsButton.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				LinearLayout layout = new LinearLayout(PushDemoActivity.this);
				layout.setOrientation(LinearLayout.VERTICAL);

				final EditText textviewGid = new EditText(PushDemoActivity.this);
				textviewGid.setHint(R.string.tags_hint);
				layout.addView(textviewGid);

				AlertDialog.Builder builder = new AlertDialog.Builder(
						PushDemoActivity.this);
				builder.setView(layout);
				builder.setPositiveButton(R.string.text_btn_setTags,
						new DialogInterface.OnClickListener() {

							public void onClick(DialogInterface dialog,
									int which) {

								String originTags = textviewGid.getText()
										.toString();
								List<String> tags = new ArrayList<String>();
								int indexOfComma = originTags.indexOf(',');
								String tag;
								while (indexOfComma != -1) {
									tag = originTags.substring(0, indexOfComma);
									tags.add(tag);

									originTags = originTags
											.substring(indexOfComma + 1);
									indexOfComma = originTags.indexOf(',');
								}

								tags.add(originTags);
								PushManager.setTags(getApplicationContext(),
										tags);
							}
						});
				builder.show();

			}
		});

		delTagsButton.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				LinearLayout layout = new LinearLayout(PushDemoActivity.this);
				layout.setOrientation(LinearLayout.VERTICAL);

				final EditText textviewGid = new EditText(PushDemoActivity.this);
				textviewGid.setHint(R.string.tags_hint);
				layout.addView(textviewGid);

				AlertDialog.Builder builder = new AlertDialog.Builder(
						PushDemoActivity.this);
				builder.setView(layout);
				builder.setPositiveButton(R.string.text_btn_delTags,
						new DialogInterface.OnClickListener() {

							public void onClick(DialogInterface dialog,
									int which) {

								String originTags = textviewGid.getText()
										.toString();
								List<String> tags = new ArrayList<String>();
								int indexOfComma = originTags.indexOf(',');
								String tag;
								while (indexOfComma != -1) {
									tag = originTags.substring(0, indexOfComma);
									tags.add(tag);

									originTags = originTags
											.substring(indexOfComma + 1);
									indexOfComma = originTags.indexOf(',');
								}

								tags.add(originTags);
								PushManager.delTags(getApplicationContext(),
										tags);

							}
						});
				builder.show();

			}
		});

		richButton.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {
				Intent sendIntent = new Intent();
				sendIntent.setClass(PushDemoActivity.this,
						MediaListActivity.class);
				sendIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				PushDemoActivity.this.startActivity(sendIntent);
			}
		});

		PushConstants.restartPushService(this);
	}

	@Override
	public void onStart() {
		super.onStart();
		Log.d(TAG, ">=====onStart=====<");

		Intent recIntent = this.getIntent();
		String openType = ""
				+ recIntent.getIntExtra(PushConstants.EXTRA_OPENTYPE, 0);
		String msgId = recIntent.getStringExtra(PushConstants.EXTRA_MSGID);

		Log.d(TAG,
				"Collect Activity start feedback info , package:"
						+ this.getPackageName() + " openType: " + openType
						+ " msgid: " + msgId);

		PushManager.activityStarted(this);
	}

	@Override
	public void onResume() {
		super.onResume();

		showChannelIds();
	}

	@Override
	protected void onNewIntent(Intent intent) {
		// 如果要统计Push引起的用户使用应用情况，请实现本方法，且加上这一个语句
		setIntent(intent);
		
		handleIntent(intent);
	}

	@Override
	public void onStop() {
		super.onStop();
		Log.d(TAG, ">=====onStop=====<");
		PushManager.activityStoped(this);
	}

	/**
	 * 处理Intent
	 * 
	 * @param intent
	 *            intent
	 */
	private void handleIntent(Intent intent) {
		String action = intent.getAction();
		Log.d(TAG, "Handle intent: \r\n" + intent);

		if (ACTION_RESPONSE.equals(action)) {

			String method = intent.getStringExtra(RESPONSE_METHOD);

			if (PushConstants.METHOD_BIND.equals(method)) {
				Log.d(TAG, "Handle bind response");
				String toastStr = "";
				int errorCode = intent.getIntExtra(RESPONSE_ERRCODE, 0);
				if (errorCode == 0) {
					String content = intent.getStringExtra(RESPONSE_CONTENT);
					String appid = "";
					String channelid = "";
					String userid = "";

					try {
						JSONObject jsonContent = new JSONObject(content);
						JSONObject params = jsonContent
								.getJSONObject("response_params");
						appid = params.getString("appid");
						channelid = params.getString("channel_id");
						userid = params.getString("user_id");
					} catch (JSONException e) {
						Log.e(TAG, "Parse bind json infos error: " + e);
					}

					SharedPreferences sp = PreferenceManager
							.getDefaultSharedPreferences(this);
					Editor editor = sp.edit();
					editor.putString("appid", appid);
					editor.putString("channel_id", channelid);
					editor.putString("user_id", userid);
					editor.commit();

					showChannelIds();

					toastStr = "Bind Success";
				} else {
					toastStr = "Bind Fail, Error Code: " + errorCode;
					if (errorCode == 30607) {
						Log.d("Bind Fail", "update channel token-----!");
					}
				}

				Toast.makeText(this, toastStr, Toast.LENGTH_LONG).show();
			}
		} else if (ACTION_LOGIN.equals(action)) {
			String accessToken = intent.getStringExtra(EXTRA_ACCESS_TOKEN);
			PushManager.startWork(getApplicationContext(), PushConstants.LOGIN_TYPE_ACCESS_TOKEN, accessToken);
			isLogin = true;
			initButton.setText(R.string.text_btn_init1);
		} else if (ACTION_MESSAGE.equals(action)) {
			String message = intent.getStringExtra(EXTRA_MESSAGE);
			String summary = "Receive message from server:\n\t";
			JSONObject contentJson = null;
			String contentStr = message;
			try {
				contentJson = new JSONObject(message);
				contentStr = contentJson.toString(4);
			} catch (JSONException e) {
				Log.d(TAG, "Parse message json exception.");
			}
			summary += contentStr;
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setMessage(summary);
			builder.setCancelable(true);
			Dialog dialog = builder.create();
			dialog.setCanceledOnTouchOutside(true);
			dialog.show();
		} else {
			Log.i(TAG, "Activity normally start!");
		}
	}

	private void showChannelIds() {
		String appId = null;
		String channelId = null;
		String clientId = null;

		SharedPreferences sp = PreferenceManager
				.getDefaultSharedPreferences(this);
		appId = sp.getString("appid", "");
		channelId = sp.getString("channel_id", "");
		clientId = sp.getString("user_id", "");
		text = (TextView) findViewById(R.id.text);

		String content = "\tApp ID: " + appId + "\n\tChannel ID: " + channelId
				+ "\n\tUser ID: " + clientId + "\n\t";
		Log.d(TAG, "Content: " + content);
		if (text != null) {
			text.setText(content);
		}
		text.invalidate();
	}
}
